package com.lemner.ke.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lemner.ke.R;
import com.lemner.ke.activity.DetailActivity;
import com.lemner.ke.adapter.LibraryLeftAdapter;
import com.lemner.ke.adapter.LibraryRightAdapter;
import com.lemner.ke.adapter.RecommendRecAdapter;
import com.lemner.ke.adapter.SpinnerLeftAdapter;
import com.lemner.ke.base.BaseFragment;
import com.lemner.ke.base.BaseListBean;
import com.lemner.ke.base.BaseListener;
import com.lemner.ke.base.BaseObjectBean;
import com.lemner.ke.base.BasePageBean;
import com.lemner.ke.bean.RecommendBean;
import com.lemner.ke.bean.RichClassifyBean;
import com.lemner.ke.bean.RichClassifyListBean;
import com.lemner.ke.model.library.GetEntityListModel;
import com.lemner.ke.model.library.GetRichClassifyListModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;

import butterknife.internal.Utils;

/**
 * 库
 *
 * @author raintea
 * @date 2018/9/18
 */
public class LibraryFragment extends BaseFragment {

    private boolean isViewCreated;//视图是否已经创建

    RecyclerView leftRec;
    LinearLayout layoutleft;
    public LinearLayout layoutright;
    PopupWindow leftPopup, rightPopup;
    View foreground;
    TextView Tvleft, Tvright;

    List<String> left = new ArrayList<String>();
    LibraryLeftAdapter libraryLeftAdapter;
    LibraryRightAdapter libraryRightAdapter;

    //网络数据
    List<RichClassifyListBean> Richlist;
    //库的列表
    RecyclerView libRec;
    //记录二级联动位置
    int current = 0;

    //本页rec
    RecommendRecAdapter recommendRecAdapter;

    //记录ids
    public String mLeftpop="createtime";
    public String mRightR = "";
    public String mRightRParent="";
    public String mRightL = "";
    public String keywords="";
    //第一页
    public int cur_page = 1;
    public static LibraryFragment getInstance() {
        return new LibraryFragment();
    }

    @Override
    public int getLayoutFile() {

        return R.layout.fragment_library;
    }

    @Override
    public void initSetting() {
        if (!isViewCreated) {
            left.add("综合排序");
            left.add("人气排行");
            left.add("热度排行");
        }
        isViewCreated = true;

    }

    @Override
    public void initView() {

        layoutleft = findViewById(R.id.ll_library_left);
        layoutright = findViewById(R.id.ll_library_right);
        Tvleft = findViewById(R.id.tv_library_left);
        Tvright = findViewById(R.id.tv_library_right);
        libRec = findViewById(R.id.rv_library_data);


    }

    @Override
    public void initEvent() {
        layoutleft.setOnClickListener(this);
        layoutright.setOnClickListener(this);
    }

    @Override
    public void initData() {
        initLeftPop();
        initRightPop();
        LinearLayoutManager manager = new LinearLayoutManager(getContext());

        recommendRecAdapter = new RecommendRecAdapter(R.layout.item_new_knowledge);
//        recommendRecAdapter.disableLoadMoreIfNotFullPage();
        libRec.setLayoutManager(manager);

        recommendRecAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                libRec.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cur_page++;
                        addDataList(mRightRParent, mRightR, keywords, mLeftpop);
                    }
                },2);
            }
        },libRec);

        //条目跳转
        recommendRecAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                RecommendBean bean= (RecommendBean) adapter.getItem(position);
                Intent intent=new Intent(getContext(),DetailActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("recommend",bean);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        libRec.setAdapter(recommendRecAdapter);


        foreground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftPopup.dismiss();
            }
        });
        upDateList("","" , keywords, "createtime");
        new GetRichClassifyListModel().getRichClassifyList(new BaseListener<BaseListBean<RichClassifyListBean>>() {
            @Override
            public void onResponse(BaseListBean<RichClassifyListBean> beanList) {
                RichClassifyListBean richClassifyListBean = new RichClassifyListBean();
                richClassifyListBean.setSubclassify(new ArrayList<RichClassifyBean>());
                RichClassifyBean richClassifyBean = new RichClassifyBean();
                richClassifyBean.setTitle("全部");
                richClassifyListBean.getSubclassify().add(0, richClassifyBean);
                for (int i = 0; i < beanList.getData().size(); i++) {

                    richClassifyListBean.getSubclassify().addAll(beanList.getData().get(i).getSubclassify());

                    beanList.getData().get(i).getSubclassify().add(0, richClassifyBean);
                }
                richClassifyListBean.setTitle("全部课程");
                Richlist = beanList.getData();
                Richlist.add(0, richClassifyListBean);
                libraryLeftAdapter.addData(Richlist);
                libraryRightAdapter.addData(Richlist.get(0).getSubclassify());

            }

            @Override
            public void onFail(String msg) {

            }
        });


    }

    private void initRightPop() {

        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.pop_right, null);
        rightPopup = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        rightPopup.setFocusable(true);
        rightPopup.setOutsideTouchable(true);
        rightPopup.setTouchable(true);
        rightPopup.setBackgroundDrawable(new BitmapDrawable());


        RecyclerView recLeft = inflate.findViewById(R.id.rv_pop_left);
        RecyclerView recRight = inflate.findViewById(R.id.rv_pop_right);
        libraryRightAdapter = new LibraryRightAdapter(R.layout.item_library_right);
        libraryLeftAdapter = new LibraryLeftAdapter(R.layout.item_library_left);


        libraryLeftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                cur_page=1;//重置页数
                libraryLeftAdapter.setPostion(position);
                libraryLeftAdapter.notifyDataSetChanged();
                libraryRightAdapter.setNewData(Richlist.get(position).getSubclassify());
                current = position;
            }
        });
        libraryRightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                cur_page=1;//重置页数
                RichClassifyBean richClassifyBean = Richlist.get(current).getSubclassify().get(position);
                Tvright.setText(richClassifyBean.getTitle());

                upDateList(richClassifyBean.getParentids(),richClassifyBean.getIds(), keywords, mLeftpop);
                mRightR=richClassifyBean.getIds();
                mRightRParent=richClassifyBean.getParentids();
                rightPopup.dismiss();
            }
        });

        LinearLayoutManager managerLeft = new LinearLayoutManager(getContext());
        recLeft.setLayoutManager(managerLeft);
        recLeft.setAdapter(libraryLeftAdapter);
        LinearLayoutManager managerRight = new LinearLayoutManager(getContext());
        recRight.setLayoutManager(managerRight);
        recRight.setAdapter(libraryRightAdapter);
    }

    private void initLeftPop() {

        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.pop_left, null);
        leftPopup = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        leftPopup.setFocusable(true);
        // 设置PopupWindow是否能响应外部点击事件
        leftPopup.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        leftPopup.setTouchable(true);
        leftPopup.setBackgroundDrawable(new BitmapDrawable());
        Tvleft.setText(left.get(0));
        foreground = inflate.findViewById(R.id.pop_left_foreground);
        leftRec = inflate.findViewById(R.id.rv_pop_spinner);


        final SpinnerLeftAdapter spinnerLeftAdapter = new SpinnerLeftAdapter(R.layout.item_spinner_dropdown, left);

        spinnerLeftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                spinnerLeftAdapter.setPostion(position);
                Tvleft.setText(left.get(position));
                cur_page=1;//重置页数
                switch (position) {
                    case 0:
                        upDateList(mRightRParent, mRightR, keywords, "createtime");
                        mLeftpop="createtime";
                        break;
                    case 1:
                        upDateList(mRightRParent, mRightR, keywords, "likesNum");
                        mLeftpop="likesNum";
                        break;
                    case 2:
                        upDateList(mRightRParent, mRightR, keywords, "hitNum");
                        mLeftpop="hitNum";
                        break;
                    default:
                }
                spinnerLeftAdapter.notifyDataSetChanged();
                leftPopup.dismiss();
            }
        });

        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        leftRec.setLayoutManager(layoutManager);
        leftRec.setAdapter(spinnerLeftAdapter);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_library_left:
                showAsDropDown(leftPopup, v, 0, 0);
                // leftPopup.showAsDropDown(v);
                break;
            case R.id.ll_library_right:
                showAsDropDown(rightPopup, v, 0, 0);
                //   rightPopup.showAsDropDown(v);
                break;
            default:
        }
    }

    public void upDateList(String firstIds, String secondIds, String keywords, String orderColunm) {
        new GetEntityListModel().getEntityList(cur_page, firstIds, secondIds, keywords, orderColunm, "desc", new BaseListener() {
            @Override
            public void onResponse(Object o) {
                BaseObjectBean<BasePageBean<RecommendBean>> bean = (BaseObjectBean<BasePageBean<RecommendBean>>) o;
                List<RecommendBean> list = bean.getData().getList();
                recommendRecAdapter.setNewData(list);


//                hasNextPage = bean.getData().getHasNextPage();
//                if (list == null || list.size() == 0) {
//                    list = bean.getData().getList();
//                    entityListAdapter.setList(list);
//                } else {
//                    entityListAdapter.addList(bean.getData().getList());
//                }
//                isfinish = true;
            }

            @Override
            public void onFail(String msg) {
//                entityListAdapter.setList(list);
//                entityListAdapter.notifyDataSetChanged();
//                isfinish = true;
            }
        });
    }
    public void addDataList(String firstIds, String secondIds, String keywords, String orderColunm) {
        new GetEntityListModel().getEntityList(cur_page, firstIds, secondIds, keywords, orderColunm, "desc", new BaseListener() {
            @Override
            public void onResponse(Object o) {
                BaseObjectBean<BasePageBean<RecommendBean>> bean = (BaseObjectBean<BasePageBean<RecommendBean>>) o;
                List<RecommendBean> list = bean.getData().getList();
                if (list!=null){
                    recommendRecAdapter.addData(list);
                    recommendRecAdapter.loadMoreComplete();
                }else{
                    recommendRecAdapter.loadMoreEnd();
                }


//                hasNextPage = bean.getData().getHasNextPage();
//                if (list == null || list.size() == 0) {
//                    list = bean.getData().getList();
//                    entityListAdapter.setList(list);
//                } else {
//                    entityListAdapter.addList(bean.getData().getList());
//                }
//                isfinish = true;
            }

            @Override
            public void onFail(String msg) {
//                entityListAdapter.setList(list);
//                entityListAdapter.notifyDataSetChanged();
//                isfinish = true;
            }
        });

    }
    /**
     * 由于Android 7.0以上(包含8.0), popupWindow弹窗位置异常这是修复代码
     *
     * @param pw     popupWindow
     * @param anchor v
     * @param xoff   x轴偏移
     * @param yoff   y轴偏移
     */
    public void showAsDropDown(final PopupWindow pw, final View anchor, final int xoff, final int yoff) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            pw.setHeight(height);
            pw.showAsDropDown(anchor, xoff, yoff);
        } else {
            pw.showAsDropDown(anchor, xoff, yoff);
        }
    }
}
